/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
 */

package com.huawei.idea.share;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.huawei.idea.ideasharesdk.object.AppInfo;
import com.huawei.idea.ideasharesdk.object.ConnectInfo;
import com.huawei.idea.ideasharesdk.object.ConnectResult;
import com.huawei.idea.ideasharesdk.object.DeviceType;
import com.huawei.idea.ideasharesdk.object.DiscoverResult;
import com.huawei.idea.ideasharesdk.object.LogInfo;
import com.huawei.idea.ideasharesdk.object.LogLevel;
import com.huawei.idea.ideasharesdk.object.RemoteServiceStatus;
import com.huawei.idea.ideasharesdk.object.ShareStatus;
import com.huawei.idea.ideasharesdk.sdk.Callback;
import com.huawei.idea.ideasharesdk.sdk.IShareServiceController;
import com.huawei.idea.ideasharesdk.sdk.ShareServiceController;
import com.huawei.idea.ideasharesdk.utils.LogUtil;

/**
 * 全局异常捕获
 *
 * @author w00415409
 * @since 2021/2/10
 */
public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int REQUEST_CODE_FOR_OVERLAY_PERMISSION = 0x201;

    private static final int ERROR_SIGNAL = 0;

    private IShareServiceController shareServiceController;

    private RadioGroup modeRadioGroup;

    private LinearLayout euaLayout;

    private EditText euaIp;

    private EditText euaPort;

    private EditText projectionCode;

    private Spinner spinner;

    private boolean isOnlineMode = false;

    private LogLevel printLogLevel = LogLevel.DEBUG;

    private String path = "";

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == ERROR_SIGNAL) {
                int retCode = msg.arg1;
                ShowErrorUtil.showErrorMsg(getApplicationContext(), retCode);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(MainActivity.this)) {
                startOnePixelWindowService();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_FOR_OVERLAY_PERMISSION);
            }
        } else {
            startOnePixelWindowService();
        }

        spinner = findViewById(R.id.id_log_spinner);
        modeRadioGroup = findViewById(R.id.id_radio_group);
        euaLayout = findViewById(R.id.id_layout_eua);
        euaIp = findViewById(R.id.id_eua_ip);
        euaPort = findViewById(R.id.id_eua_port);
        projectionCode = findViewById(R.id.id_projection_code);
        projectionCode.setInputType(InputType.TYPE_CLASS_TEXT);
        projectionCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
        path = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
        // 初始化异常处理
        DemoExceptionHandler.getInstance().init(getApplicationContext(), path);
        // 设置日志下拉框
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LogInfo logInfo = new LogInfo(path, printLogLevel, true);
                switch (position) {
                    case 1:
                        printLogLevel = LogLevel.INFO;
                        break;
                    case 2:
                        printLogLevel = LogLevel.WARNING;
                        break;
                    case 3:
                        printLogLevel = LogLevel.ERROR;
                        break;
                    default:
                        printLogLevel = LogLevel.DEBUG;
                        break;
                }
                logInfo.setLogLevel(printLogLevel);
                if (shareServiceController != null) {
                    shareServiceController.setLog(logInfo);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                printLogLevel = LogLevel.DEBUG;
            }
        });
        // 初始化屏幕操作对象
        LogInfo logInfo = new LogInfo(path, printLogLevel, true);
        AppInfo appInfo = new AppInfo("ideaShareDemo", "huohuohuo");
//        appInfo.setLogInfo(logInfo);
        shareServiceController = ShareServiceController.create(getApplicationContext(), appInfo, new IShareServiceController.IShareEventHandler() {
            @Override
            public void onRemoteServiceStatusChangedNotify(RemoteServiceStatus remoteServiceStatus) {
                DemoApp.getInstance().notifyRemoteServiceStatusChanged(remoteServiceStatus);
            }

            @Override
            public void onShareStatusChangedNotify(ShareStatus status, int reason) {
                DemoApp.getInstance().notifyShareStatusChanged(status);
            }
        });
        // 设置 RadioGroup 监听事件
        modeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 在线模式
                if (checkedId == R.id.id_radio_online) {
                    LogUtil.debug(TAG, "onCheckedChanged: online mode...");
                    isOnlineMode = true;
                    euaLayout.setVisibility(View.VISIBLE);
                } else {
                    // 离线模式
                    LogUtil.debug(TAG, "onCheckedChanged: offline mode...");
                    isOnlineMode = false;
                    euaLayout.setVisibility(View.GONE);
                    euaIp.setText("");
                    euaPort.setText("");
                }
            }
        });
        // 设置兼容性
        shareServiceController.setCompatibility(true);
        int res = shareServiceController.setDeviceType(DeviceType.NON_PROJECTOR);
        LogUtil.debug(TAG, "result = " + res);
    }

    private void startOnePixelWindowService() {
        Intent intent = new Intent(MainActivity.this, OnePixelWindowService.class);
        startService(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_FOR_OVERLAY_PERMISSION
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && Settings.canDrawOverlays(MainActivity.this)) {
            startOnePixelWindowService();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shareServiceController.destroy();
    }

    /**
     * 点击连接
     *
     * @param view view
     */
    public void connectClick(View view) {
        if (shareServiceController != null) {
            String ipAddr = "";
            int port = 144;
            if (isOnlineMode) {
                ipAddr = euaIp.getText().toString();
                try {
                    port = Integer.parseInt(euaPort.getText().toString());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            int rest = shareServiceController.discover(projectionCode.getText().toString(), ipAddr, port, new Callback<DiscoverResult>() {
                @Override
                public void onSuccess(DiscoverResult discoverResult) {
                    LogUtil.info(TAG, "discoverResult: " + discoverResult);
                    LogUtil.info(TAG, "discoverResult array len: " + discoverResult.getAddressArray().length);
                    ConnectInfo connectInfo = new ConnectInfo();
                    connectInfo.setAddressArray(discoverResult.getAddressArray());
                    connectInfo.setAddressNum(discoverResult.getAddressNum());
                    connectInfo.setPassword(discoverResult.getPassword());
                    shareServiceController.connect(connectInfo, new Callback<ConnectResult>() {
                        @Override
                        public void onSuccess(ConnectResult connectResult) {
                            // 跳转到控制页面
                            Intent connectIntent = new Intent(getBaseContext(), RemoteActivity.class);
                            String deviceName = "";
                            if (connectResult.getDevName() != null) {
                                deviceName = connectResult.getDevName();
                            }
                            connectIntent.putExtra("deviceName", deviceName);
                            startActivity(connectIntent);
                        }

                        @Override
                        public void onFailed(int retCode, String desc) {
                            sendErrorSignal(retCode);
                        }
                    });
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    sendErrorSignal(retCode);
                }
            });
            LogUtil.info(TAG, "discoverOnClick: " + rest);
        }
    }

    private void sendErrorSignal(int retCode) {
        Message msg = new Message();
        msg.what = ERROR_SIGNAL;
        msg.arg1 = retCode;
        handler.sendMessage(msg);
    }
}
